package com.punai.customer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.constant.Constants;
import com.punai.common.core.domain.BaseEntity;
import com.punai.common.core.domain.CommonConstants;
import com.punai.common.core.domain.entity.SysDictData;
import com.punai.common.core.domain.entity.SysUser;
import com.punai.common.core.domain.model.LoginUser;
import com.punai.common.exception.ServiceException;
import com.punai.common.properties.SqliteUpPathConfig;
import com.punai.common.utils.DictUtils;
import com.punai.common.utils.SecurityUtils;
import com.punai.common.utils.StringUtils;
import com.punai.common.utils.ZipUtils;
import com.punai.common.utils.sqlite.SqliteUtil;
import com.punai.customer.domain.*;
import com.punai.customer.domain.contants.CusConstants;
import com.punai.customer.domain.sqlitebo.*;
import com.punai.customer.domain.temporary.*;
import com.punai.customer.domain.vo.CusAllVo;
import com.punai.customer.domain.vo.CusCountDifferenceVo;
import com.punai.customer.domain.vo.CusImpVo;
import com.punai.customer.excelparse.ExcelChapterVo;
import com.punai.customer.excelparse.ExcelItemVo;
import com.punai.customer.excelparse.ExcelListener;
import com.punai.customer.mapper.*;
import com.punai.customer.service.ICusImportService;
import com.punai.gk.domain.GkUseData;
import com.punai.gk.mapper.GkUseDataMapper;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * CusImportService业务层处理
 *
 * @author zxw
 * @date 2022-12-27
 */
@Service
public class CusImportServiceImpl extends ServiceImpl<CusImportMapper,CusImport> implements ICusImportService
{
    @Autowired
    private CusImportMapper cusImportMapper;
    @Autowired
    private UploadFileMapper uploadFileMapper;
    @Autowired
    private CusExpenseCategoriesMapper cusExpenseCategoriesMapper;
    @Autowired
    private GkUseDataMapper gkUseDataMapper;
    @Autowired
    private CusFbChapterMapper cusFbChapterMapper;
    @Autowired
    private CusFbFeeMapper cusFbFeeMapper;
    @Autowired
    private CusFeatureMapper cusFeatureMapper;
    @Autowired
    private CusGxChapterMapper cusGxChapterMapper;
    @Autowired
    private CusGxFeeMapper cusGxFeeMapper;
    @Autowired
    private CusLinkFbFeatureMapper cusLinkFbFeatureMapper;
    @Autowired
    private CusLinkFbGxMapper cusLinkFbGxMapper;
    @Autowired
    private CusLinkFeatureMapper cusLinkFeatureMapper;
    @Autowired
    private CusLinkFeatureAssetMapper cusLinkFeatureAssetMapper;
    @Autowired
    private CusLinkGxfeeCategoryMapper cusLinkGxfeeCategoryMapper;
    @Autowired
    private CusMaterialChapterMapper cusMaterialChapterMapper;
    @Autowired
    private CusMaterialItemMapper cusMaterialItemMapper;
    @Autowired
    private CusMechanicalChapterMapper cusMechanicalChapterMapper;
    @Autowired
    private CusMechanicalItemMapper cusMechanicalItemMapper;

    @Autowired
    private CusMechanicalStaChapterMapper cusMechanicalStaChapterMapper;
    @Autowired
    private CusMechanicalStaItemMapper cusMechanicalStaItemMapper;
    @Autowired
    private CusLinkMechanicalStaCusMapper cusLinkMechanicalStaCusMapper;

    @Autowired
    private CusMaterialCuChapterMapper cusMaterialCuChapterMapper;
    @Autowired
    private CusMaterialCuItemMapper cusMaterialCuItemMapper;
    @Autowired
    private CusLinkSubpkConsumeAddressMapper cusLinkSubpkConsumeAddressMapper;
    @Autowired
    private CusLinkSubpkConsumeMapper cusLinkSubpkConsumeMapper;
    @Autowired
    private CusGxLinkGkMapper cusGxLinkGkMapper;
    @Autowired
    private CusGxLinkGkCategoriesMapper cusGxLinkGkCategoriesMapper;
    @Autowired
    private CusGxFeatureConsumeMapper cusGxFeatureConsumeMapper;
    @Autowired
    private ShortDifferenceMapper shortDifferenceMapper;

    /**
     * 查询CusImport
     *
     * @param id CusImport主键
     * @return CusImport
     */
    @Override
    public CusImport selectCusImportById(String id)
    {
        return cusImportMapper.selectCusImportById(id);
    }

    /**
     * 查询CusImport列表
     *
     * @param cusImport CusImport
     * @return CusImport
     */
    @Override
    public List<CusImport> selectCusImportList(CusImport cusImport)
    {
        Long companyId = SecurityUtils.getCompanyId();
        cusImport.setCompanyId(companyId);
        return cusImportMapper.selectCusImportList(cusImport);
    }


    private void setCreateContent(BaseEntity baseEntity) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        String username = user.getUserName();
        String nickName = user.getNickName();
        String byUser = username + Constants.NAME_SEPARATOR + nickName;
        Date now = new Date();
        baseEntity.setCreateBy(byUser);
        baseEntity.setUpdateBy(byUser);
        baseEntity.setCreateTime(now);
        baseEntity.setUpdateTime(now);
    }


    /**
     * 新增CusImport
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCusImport(CusImpVo vo)
    {
        Long companyId = SecurityUtils.getCompanyId();
        String fileId = vo.getFileId();
        if(StringUtils.isEmpty(fileId)){
            throw new ServiceException("请先上传文件");
        }
        UploadFile uploadFile = uploadFileMapper.selectById(fileId);
        String fileName = uploadFile.getFileName();
        String fileSize = uploadFile.getFileSize();
        String filePath = uploadFile.getFilePath();
        String path = SqliteUpPathConfig.getCuspath();
        StringBuilder sb = new StringBuilder();

        // 校验格式
        String temp[]=fileName.split("\\.");
        String fileNameNow=temp[temp.length-1];
        if(!StringUtils.equals(fileNameNow,"dat")){
            throw new ServiceException("请上传格式为dat的文件");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();
        Long deptId = loginUser.getDeptId();
        if (deptId == null ) {
            deptId = -999L;
        }

        SqliteUtil sqliteUtil = new SqliteUtil();
        sqliteUtil.getConnection(path + "/" + filePath);

        String sql = "SELECT * FROM GK";
        List<GK> gks = sqliteUtil.selectListRecord(GK.class, sql);
        List<GkUseData> gkInserts = new ArrayList<>(gks.size());
        Set<String> gkInsertCount = new HashSet<>();

        if(CollUtil.isEmpty(gks)){
            throw new ServiceException("请上传2023-05-15之后下载的文件");
        }

        List<String> gkLinkIdList = gkUseDataMapper.selectLinkIdList(companyId);
        for (GK gk : gks) {
            if (!gkLinkIdList.contains(gk.getLINKID())) {
                GkUseData gkUseData = new GkUseData();
                gkUseData.setId(gk.getID());
                gkUseData.setCompanyId(companyId);
                gkUseData.setCodeDesc(gk.getCODEDESC());
                gkUseData.setValueStr(gk.getVALUESTR());
                gkUseData.setNameStr(gk.getNAMESTR());
                gkUseData.setDeptId(deptId);
                gkUseData.setUserId(userId);
                gkUseData.setOrderNum(gk.getORDERNUM());
                gkUseData.setTemplateId(gk.getTEMPLATEID());
                gkUseData.setLinkId(gk.getLINKID());
                gkInserts.add(gkUseData);

                gkInsertCount.add(gk.getLINKID());
            }
        }
        if (CollUtil.isNotEmpty(gkInserts)) {
            sb.append("新增归口字典数据"+gkInsertCount.size()+"条;");
            gkUseDataMapper.insertBatchSomeColumn(gkInserts);
            gkInserts.clear();
            gks.clear();
            gkInsertCount.clear();
        }

        // 材机分类
        sql = "SELECT * FROM LB";
        List<LB> lbs = sqliteUtil.selectListRecord(LB.class, sql);
        List<CusExpenseCategories> cecs = new ArrayList<>(lbs.size());

        List<String> categoriesExistIds = cusExpenseCategoriesMapper.selectIdList(companyId);

        for (LB lb : lbs) {
            if (!categoriesExistIds.contains(lb.getID())) {
                CusExpenseCategories cec = new CusExpenseCategories();
                cec.setId(lb.getID());
                cec.setCompanyId(companyId);
                cec.setCategoriesName(lb.getMC());
                cec.setSpec(lb.getGGXH());
                cec.setUnit(lb.getDW());
                cec.setType(lb.getTYPE());
                cec.setGkItem(lb.getGKITEM());
                cecs.add(cec);
            }
        }

        if (CollUtil.isNotEmpty(cecs)) {
            sb.append("新增材机类别"+cecs.size()+"条;");
            cusExpenseCategoriesMapper.insertBatchSomeColumn(cecs);
            cecs.clear();
            lbs.clear();
            categoriesExistIds.clear();
        }

        sql = "SELECT * FROM TZ";
        List<TZ> tzs = sqliteUtil.selectListRecord(TZ.class, sql);
        List<CusFeature> features = new ArrayList<>(tzs.size());

        List<String> featureIdList = cusFeatureMapper.selectIdList(companyId);
        for (TZ tz : tzs) {
            if (!featureIdList.contains(tz.getID())) {
                CusFeature feature = new CusFeature();
                feature.setId(tz.getID());
                feature.setCompanyId(companyId);
                feature.setFeatureName(tz.getMC());
                feature.setAliasName(tz.getBIEMING());
                feature.setFeatureValues(tz.getMJTZZ());
                feature.setType(tz.getLX());
                feature.setIsInput(tz.getIsINPUT());
                feature.setCalcFlag(tz.getIsJS());
                feature.setIsNameFeature(tz.getIsMC());
                feature.setOrderNum(tz.getPX());
                setCreateContent(feature);
                feature.setUserId(userId);
                feature.setDeptId(deptId);
                features.add(feature);
            }
        }
        if (CollUtil.isNotEmpty(features)) {
            sb.append("新增特征"+features.size()+"条;");
            cusFeatureMapper.insertBatchSomeColumn(features);
            features.clear();
            tzs.clear();
            featureIdList.clear();
        }


        // 先判断下 材料机械 是否有值
        Long clALong = cusMaterialCuChapterMapper.selectCount(
                Wrappers.<CusMaterialCuChapter>lambdaQuery()
                        .eq(CusMaterialCuChapter::getCompanyId,companyId)
        );
        // 换算
        if (clALong == 0) {
            // 材料
            int pageNum = 1;
            int pageSize = 10000;
            sql = "SELECT * FROM CL_FYX limit " + 0 + "," + pageSize;
            List<CL_FYX> cl_fyxes = sqliteUtil.selectListRecord(CL_FYX.class, sql);

            while (CollUtil.isNotEmpty(cl_fyxes)) {
                List<CusMaterialCuItem> materialItems = new ArrayList<>();
                for (CL_FYX cl_fyx : cl_fyxes) {
                    CusMaterialCuItem cmi = new CusMaterialCuItem();
                    cmi.setId(cl_fyx.getID());
                    cmi.setCode(cl_fyx.getBM());
                    cmi.setCompanyId(companyId);
                    cmi.setChapterId(cl_fyx.getFLID());
                    cmi.setItemName(cl_fyx.getMC());
                    cmi.setUnit(cl_fyx.getDW());
                    cmi.setSpec(cl_fyx.getGGXH());
                    cmi.setCoefficientUnit(cl_fyx.getHSDW());
                    cmi.setCoefficientSpec(cl_fyx.getHSGG());
                    cmi.setSpecificationConversion(cl_fyx.getGGXHXS());
                    cmi.setOrderNum(cl_fyx.getPX());
                    cmi.setIsMatching(cl_fyx.getIsPB());
                    cmi.setIsBeton(cl_fyx.getIsHNT());
                    setCreateContent(cmi);
                    cmi.setUserId(userId);
                    cmi.setDeptId(deptId);
                    materialItems.add(cmi);
                }

                if (materialItems.size() == 10000) {
                    cusMaterialCuItemMapper.insertBatchSomeColumn(materialItems);
                    materialItems.clear();
                    pageNum ++ ;
                    sql = "SELECT * FROM CL_FYX limit " + (pageNum-1)*pageSize + "," + pageSize;
                    cl_fyxes = sqliteUtil.selectListRecord(CL_FYX.class, sql);
                }
                if (CollUtil.isNotEmpty(materialItems)) {
                    cusMaterialCuItemMapper.insertBatchSomeColumn(materialItems);
                    materialItems.clear();
                    cl_fyxes.clear();
                }
            }

            sql = "SELECT * FROM CL_ZJ";
            List<CL_ZJ> cl_zjs = sqliteUtil.selectListRecord(CL_ZJ.class, sql);
            List<CusMaterialCuChapter> cmcs = new ArrayList<>();
            for (CL_ZJ cl_zj : cl_zjs) {
                CusMaterialCuChapter cmc = new CusMaterialCuChapter();
                cmc.setId(cl_zj.getID());
                cmc.setCompanyId(companyId);
                cmc.setChapterName(cl_zj.getMC());
                cmc.setPid(cl_zj.getPID());
                cmc.setPids(cl_zj.getPIDS());
                setCreateContent(cmc);
                cmc.setUserId(userId);
                cmc.setDeptId(deptId);
                cmc.setOrderNum(cl_zj.getPX());
                cmcs.add(cmc);
            }
            if (CollUtil.isNotEmpty(cmcs)) {
                sb.append("导入材料费用项与章节");
                cusMaterialCuChapterMapper.insertBatchSomeColumn(cmcs);
                cmcs.clear();
                cl_zjs.clear();
            }

        }

        Long jxALong = cusMechanicalStaChapterMapper.selectCount(
                Wrappers.<CusMechanicalStaChapter>lambdaQuery()
                        .eq(CusMechanicalStaChapter::getCompanyId, companyId)
        );
        if (jxALong == 0) {
            sql = "SELECT * FROM JX_FYX";
            List<JX_FYX> jx_fyxes = sqliteUtil.selectListRecord(JX_FYX.class, sql);

            List<CusMechanicalStaItem> cmis = new ArrayList<>();
            for (JX_FYX jx_fyx : jx_fyxes) {
                CusMechanicalStaItem cmi = new CusMechanicalStaItem();
                cmi.setId(jx_fyx.getBM());
                cmi.setCompanyId(companyId);
                cmi.setChapterId(jx_fyx.getFLID());
                cmi.setItemName(jx_fyx.getMC());
                cmi.setUnit(jx_fyx.getDW());
                cmi.setSpec(jx_fyx.getGGXH());
                cmi.setOrderNum(jx_fyx.getPX());
                setCreateContent(cmi);
                cmi.setUserId(userId);
                cmi.setDeptId(deptId);
                cmis.add(cmi);
            }
            if (CollUtil.isNotEmpty(cmis)) {
                sb.append("导入机械费用项;");
                cusMechanicalStaItemMapper.insertBatchSomeColumn(cmis);
                cmis.clear();
                jx_fyxes.clear();
            }

            sql = "SELECT * FROM JX_ZJ";
            List<JX_ZJ> jx_zjs = sqliteUtil.selectListRecord(JX_ZJ.class, sql);
            List<CusMechanicalStaChapter> cmcs = new ArrayList<>();
            for (JX_ZJ jx_zj : jx_zjs) {
                CusMechanicalStaChapter cmc = new CusMechanicalStaChapter();
                cmc.setId(jx_zj.getID());
                cmc.setCompanyId(companyId);
                cmc.setChapterName(jx_zj.getMC());
                cmc.setPid(jx_zj.getPID());
                cmc.setPids(jx_zj.getPIDS());
                cmc.setOrderNum(jx_zj.getPX());
                setCreateContent(cmc);
                cmc.setUserId(userId);
                cmc.setDeptId(deptId);
                cmcs.add(cmc);
            }
            if (CollUtil.isNotEmpty(cmcs)) {
                sb.append("导入机械费用项章节;");
                cusMechanicalStaChapterMapper.insertBatchSomeColumn(cmcs);
                cmcs.clear();
                jx_zjs.clear();
            }
        }


        sql = "SELECT * FROM GX_ZJ";
        List<GX_ZJ> gx_zjs = sqliteUtil.selectListRecord(GX_ZJ.class, sql);

        sql = "SELECT * FROM GX_FYX";
        List<GX_FYX> gx_fyxes = sqliteUtil.selectListRecord(GX_FYX.class, sql);

        sql = "SELECT * FROM GX_LINK_CATEGORY";
        List<GX_LINK_CATEGORY> gx_link_categories = sqliteUtil.selectListRecord(GX_LINK_CATEGORY.class, sql);

        sql = "SELECT * FROM SL_ADDRESS";
        List<SL_ADDRESS> gx_link_address = sqliteUtil.selectListRecord(SL_ADDRESS.class, sql);

        sql = "SELECT * FROM SL_CONSUME";
        List<SL_CONSUME> gx_link_consumes = sqliteUtil.selectListRecord(SL_CONSUME.class, sql);

        sql = "SELECT * FROM GX_FEATURE_CONSUME";
        List<GX_FEATURE_CONSUME> gx_feature_consumes = sqliteUtil.selectListRecord(GX_FEATURE_CONSUME.class, sql);

        sql = "SELECT * FROM GX_LINK_TZ";
        List<GX_LINK_TZ> gx_link_tzs = sqliteUtil.selectListRecord(GX_LINK_TZ.class, sql);

        sql = "SELECT * FROM GX_LINK_GK";
        List<GX_LINK_GK> gx_link_gks = sqliteUtil.selectListRecord(GX_LINK_GK.class, sql);

        sql = "SELECT * FROM GX_LINK_GK_LB";
        List<GX_LINK_GK_LB> gx_link_gk_lbs = sqliteUtil.selectListRecord(GX_LINK_GK_LB.class, sql);


        List<GX_ZJ> collect = gx_zjs.stream().filter(e -> StrUtil.equals(CommonConstants.DEF_PID, e.getPID())).collect(Collectors.toList());

        List<String> specIds = collect.stream().map(GX_ZJ::getID).collect(Collectors.toList());

        List<CusGxChapter> cusGxChapters = cusGxChapterMapper.selectList(
                Wrappers.<CusGxChapter>lambdaQuery()
                        .eq(CusGxChapter::getPid, CommonConstants.DEF_PID)
                        .in(CusGxChapter::getSpecId, specIds)
                        .eq(CusGxChapter::getCompanyId, companyId)
        );

        List<String> existSpecIds = cusGxChapters.stream().map(CusGxChapter::getSpecId).collect(Collectors.toList());

        boolean notEmpty = CollUtil.isNotEmpty(cusGxChapters);
        if (notEmpty) {
            List<String> existNames = cusGxChapters.stream().map(CusGxChapter::getName).collect(Collectors.toList());
            sb.append("标准费用项已存在专业:").append(StrUtil.join(",",existNames)).append(";");
            List<String> existIds = cusGxChapters.stream().map(CusGxChapter::getId).collect(Collectors.toList());
            gx_zjs = gx_zjs.stream().filter(e -> !existIds.contains(e.getSPECID())).collect(Collectors.toList());
            // 处理费用项
            gx_fyxes = gx_fyxes.stream().filter(e -> !existIds.contains(e.getSPECID())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(gx_fyxes)) {
                List<String> fyxIds = gx_fyxes.stream().map(GX_FYX::getID).collect(Collectors.toList());
                gx_link_categories = gx_link_categories.stream().filter(e -> fyxIds.contains(e.getFYXBM())).collect(Collectors.toList());
                gx_link_tzs = gx_link_tzs.stream().filter(e -> fyxIds.contains(e.getFYXBM())).collect(Collectors.toList());
                gx_link_gks = gx_link_gks.stream().filter(e -> fyxIds.contains(e.getGX_ID())).collect(Collectors.toList());
                gx_link_gk_lbs = gx_link_gk_lbs.stream().filter(e -> fyxIds.contains(e.getGX_ID())).collect(Collectors.toList());
            } else {
                gx_link_categories = new ArrayList<>();
                gx_link_tzs = new ArrayList<>();
                gx_link_gks = new ArrayList<>();
                gx_link_gk_lbs = new ArrayList<>();
            }
        }

        // 复制 GX
        List<CusGxChapter> gxChapters = new ArrayList<>();
        for (GX_ZJ gx_zj : gx_zjs) {
            CusGxChapter cgc = new CusGxChapter();
            cgc.setId(gx_zj.getID());
            cgc.setCompanyId(companyId);
            cgc.setSpecId(gx_zj.getSPECID());
            cgc.setName(gx_zj.getMC());
            cgc.setPid(gx_zj.getPID());
            cgc.setPids(gx_zj.getPIDS());
            cgc.setOrderNum(gx_zj.getPX());
            setCreateContent(cgc);
            cgc.setUserId(userId);
            cgc.setDeptId(deptId);
            gxChapters.add(cgc);
        }
        if (CollUtil.isNotEmpty(gxChapters)) {
            sb.append("导入标准费用项章节;");
            cusGxChapterMapper.insertBatchSomeColumn(gxChapters);
            gxChapters.clear();
            gx_zjs.clear();
        }


        List<CusGxFee> gxFees = new ArrayList<>();
        for (GX_FYX gx_fyx : gx_fyxes) {
            CusGxFee gxFee = new CusGxFee();
            gxFee.setId(gx_fyx.getID());
            gxFee.setCode(gx_fyx.getBM());
            gxFee.setCompanyId(companyId);
            gxFee.setSpecId(gx_fyx.getSPECID());
            gxFee.setFeatureConsumeState(gx_fyx.getFEATURE_CONSUME_STATE());
            gxFee.setName(gx_fyx.getMC());
            gxFee.setChapterId(gx_fyx.getFLID());
            gxFee.setUnit(gx_fyx.getDW());
            gxFee.setContent(gx_fyx.getGZNR());
            gxFee.setCalcRule(gx_fyx.getJSGZ());
            gxFee.setSuitableRange(gx_fyx.getGZFW());
            gxFee.setOrderNum(gx_fyx.getPX());
            setCreateContent(gxFee);
            gxFee.setUserId(userId);
            gxFee.setDeptId(deptId);
            gxFee.setPriority(gx_fyx.getYXJ());
            gxFees.add(gxFee);
        }
        if (CollUtil.isNotEmpty(gxFees)) {
            sb.append("导入标准费用项;");
            cusGxFeeMapper.insertBatchSomeColumn(gxFees);
            gxFees.clear();
            gx_fyxes.clear();
        }


        List<CusLinkGxfeeCategory> gxfeeCategories = new ArrayList<>();
        for (GX_LINK_CATEGORY gx_link_category : gx_link_categories) {
            CusLinkGxfeeCategory gfc = new CusLinkGxfeeCategory();
            gfc.setId(gx_link_category.getID());
            gfc.setCompanyId(companyId);
            gfc.setGxId(gx_link_category.getFYXBM());
            gfc.setCategoryId(gx_link_category.getLBID());
            gfc.setConsumption(gx_link_category.getXHL());
            gfc.setType(gx_link_category.getTYPE());
            gfc.setDelFlag("0");
            gxfeeCategories.add(gfc);
        }
        if (CollUtil.isNotEmpty(gxfeeCategories)) {
            sb.append("导入标准费用项关联材料机械类别;");
            cusLinkGxfeeCategoryMapper.insertBatchSomeColumn(gxfeeCategories);
            gxfeeCategories.clear();
            gx_link_categories.clear();
        }

        List<CusLinkFeature> linkFeatures = new ArrayList<>();
        for (GX_LINK_TZ glz : gx_link_tzs) {
            CusLinkFeature clf = new CusLinkFeature();
            clf.setId(glz.getID());
            clf.setCompanyId(companyId);
            clf.setItemId(glz.getFYXBM());
            clf.setFeatureId(glz.getTZID());
            clf.setFeatureItem(glz.getTZZ());
            clf.setType(glz.getTYPE());
            clf.setIsPrefix("N");
            clf.setSequence(0);
            clf.setOrderNum(glz.getPX());
            linkFeatures.add(clf);
        }
        if (CollUtil.isNotEmpty(linkFeatures)) {
            sb.append("导入标准费用项关联特征;");
            cusLinkFeatureMapper.insertBatchSomeColumn(linkFeatures);
            linkFeatures.clear();
            gx_link_tzs.clear();
        }

        List<CusGxLinkGk> linkGks = new ArrayList<>();
        for (GX_LINK_GK glg : gx_link_gks) {
            CusGxLinkGk gxLinkGk = new CusGxLinkGk();
            gxLinkGk.setId(glg.getID());
            gxLinkGk.setCompanyId(companyId);
            gxLinkGk.setGxId(glg.getGX_ID());
            gxLinkGk.setSpecId(glg.getSPEC_ID());
            gxLinkGk.setSubpackagePattern(glg.getSUBPACKAGE_PATTERN());
            gxLinkGk.setType(glg.getTYPE());
            gxLinkGk.setFeatureState(glg.getFEATURE_STATE());
            gxLinkGk.setFeatureId(glg.getFEATURE_ID());
            gxLinkGk.setFeatureItem(glg.getFEATURE_ITEM());
            gxLinkGk.setGkItem(glg.getGK_ITEM());
            gxLinkGk.setOrderNum(glg.getORDER_NUM());
            linkGks.add(gxLinkGk);
        }
        if (CollUtil.isNotEmpty(linkGks)) {
            sb.append("导入标准费用项关联归口;");
            cusGxLinkGkMapper.insertBatchSomeColumn(linkGks);
            linkGks.clear();
            gx_link_gks.clear();
        }
        List<CusGxLinkGkCategories> linkGkLbs = new ArrayList<>();
        for (GX_LINK_GK_LB glgl : gx_link_gk_lbs) {
            CusGxLinkGkCategories gxLinkGkLb = new CusGxLinkGkCategories();
            gxLinkGkLb.setId(glgl.getID());
            gxLinkGkLb.setSpecId(glgl.getSPEC_ID());
            gxLinkGkLb.setGxId(glgl.getGX_ID());
            gxLinkGkLb.setCompanyId(companyId);
            gxLinkGkLb.setGxLinkGkId(glgl.getGX_LINK_GK_ID());
            gxLinkGkLb.setCategoriesId(glgl.getCATEGORIES_ID());
            gxLinkGkLb.setGkItem(glgl.getGK_ITEM());
            gxLinkGkLb.setOrderNum(glgl.getORDER_NUM());
            gxLinkGkLb.setDelFlag("0");
            linkGkLbs.add(gxLinkGkLb);
        }
        if (CollUtil.isNotEmpty(linkGkLbs)) {
            cusGxLinkGkCategoriesMapper.insertBatchSomeColumn(linkGkLbs);
            linkGkLbs.clear();
            gx_link_gk_lbs.clear();
        }

        List<CusLinkSubpkConsumeAddress> cusLinkSubpkConsumeAddresses = new ArrayList<>();
        for (SL_ADDRESS sl_address : gx_link_address) {
            if(!existSpecIds.contains(sl_address.getZY())){
                CusLinkSubpkConsumeAddress linkSubpkConsumeAddress = new CusLinkSubpkConsumeAddress();
                linkSubpkConsumeAddress.setCompanyId(companyId);
                linkSubpkConsumeAddress.setSpecId(sl_address.getZY());
                linkSubpkConsumeAddress.setId(sl_address.getID());
                linkSubpkConsumeAddress.setAddress(sl_address.getDQ());
                linkSubpkConsumeAddress.setOrderNum(sl_address.getPX());
                linkSubpkConsumeAddress.setUserId(userId);
                linkSubpkConsumeAddress.setDeptId(deptId);
                setCreateContent(linkSubpkConsumeAddress);
                cusLinkSubpkConsumeAddresses.add(linkSubpkConsumeAddress);
            }
        }
        if (CollUtil.isNotEmpty(cusLinkSubpkConsumeAddresses)) {
            sb.append("导入标准费用项关联耗量地区;");
            cusLinkSubpkConsumeAddressMapper.insertBatchSomeColumn(cusLinkSubpkConsumeAddresses);
            cusLinkSubpkConsumeAddresses.clear();
            gx_link_address.clear();
        }

        List<CusGxFeatureConsume> gxFeatureConsumes = new ArrayList<>(gx_feature_consumes.size());
        for (GX_FEATURE_CONSUME gx_feature_consume : gx_feature_consumes) {
            if(!existSpecIds.contains(gx_feature_consume.getSPEC_ID())){
                CusGxFeatureConsume cusGxFeatureConsume = new CusGxFeatureConsume();
                cusGxFeatureConsume.setId(gx_feature_consume.getID());
                cusGxFeatureConsume.setCompanyId(companyId);
                cusGxFeatureConsume.setSpecId(gx_feature_consume.getSPEC_ID());
                cusGxFeatureConsume.setGxId(gx_feature_consume.getGX_ID());
                cusGxFeatureConsume.setAddress(gx_feature_consume.getADDRESS());
                cusGxFeatureConsume.setFeatureItem(gx_feature_consume.getFEATURE_ITEM());
                cusGxFeatureConsume.setDelFlag("0");
                cusGxFeatureConsume.setOrderNum(gx_feature_consume.getORDER_NUM());
                gxFeatureConsumes.add(cusGxFeatureConsume);
            }
        }
        if (CollUtil.isNotEmpty(gxFeatureConsumes)) {
            sb.append("导入标准费用项特征描述;");
            cusGxFeatureConsumeMapper.insertBatchSomeColumn(gxFeatureConsumes);
            gxFeatureConsumes.clear();
            gx_feature_consumes.clear();
        }

        List<CusLinkSubpkConsume> cusLinkSubpkConsumes = new ArrayList<>();
        for (SL_CONSUME sl_consume : gx_link_consumes) {
            if(!existSpecIds.contains(sl_consume.getZY())){
                CusLinkSubpkConsume linkSubpkConsume = new CusLinkSubpkConsume();
                linkSubpkConsume.setCompanyId(companyId);
                linkSubpkConsume.setId(sl_consume.getID());
                linkSubpkConsume.setAddress(sl_consume.getDQ());
                linkSubpkConsume.setSpecId(sl_consume.getZY());
                linkSubpkConsume.setSubpkItemId(sl_consume.getGX());
                linkSubpkConsume.setCategoriesId(sl_consume.getCJ());
                linkSubpkConsume.setReferenceConsume(sl_consume.getXHL());
                linkSubpkConsume.setRealityConsume(sl_consume.getXHL());
                linkSubpkConsume.setType(sl_consume.getLX());
                linkSubpkConsume.setLinkGxFeatureId(sl_consume.getLINK_GX_FEATURE_ID());
                linkSubpkConsume.setDelFlag("0");
                cusLinkSubpkConsumes.add(linkSubpkConsume);
            }
        }
        if (CollUtil.isNotEmpty(cusLinkSubpkConsumes)) {
            sb.append("导入标准费用项关联耗量;");
            cusLinkSubpkConsumeMapper.insertBatchSomeColumn(cusLinkSubpkConsumes);
            cusLinkSubpkConsumes.clear();
            gx_link_consumes.clear();
        }

        /**
        sql = "SELECT * FROM ZH_ZJ";
        List<ZH_ZJ> zh_zjs = sqliteUtil.selectListRecord(ZH_ZJ.class, sql);

        sql = "SELECT * FROM ZH_FYX";
        List<ZH_FYX> zh_fyxes = sqliteUtil.selectListRecord(ZH_FYX.class, sql);

        sql = "SELECT * FROM ZH_LINK_GX";
        List<ZH_LINK_GX> zh_link_gxes = sqliteUtil.selectListRecord(ZH_LINK_GX.class, sql);


        sql = "SELECT * FROM ZH_LINK_TZ";
        List<ZH_LINK_TZ> zh_link_tzs = sqliteUtil.selectListRecord(ZH_LINK_TZ.class, sql);


        if(zh_zjs.size() != 0) {
            List<ZH_ZJ> zhSpecIds = zh_zjs.stream().filter(e -> StrUtil.equals(CommonConstants.DEF_PID, e.getPID())).collect(Collectors.toList());

            List<String> zhRealSpecIds = zhSpecIds.stream().map(ZH_ZJ::getID).collect(Collectors.toList());

            List<CusFbChapter> cusFbChapters = cusFbChapterMapper.selectList(
                    Wrappers.<CusFbChapter>lambdaQuery()
                            .eq(CusFbChapter::getPid, CommonConstants.DEF_PID)
                            .in(CusFbChapter::getSpecId, zhRealSpecIds)
                            .eq(CusFbChapter::getCompanyId, companyId)
            );

            if (CollUtil.isNotEmpty(cusFbChapters)) {
                List<String> existNames = cusFbChapters.stream().map(CusFbChapter::getName).collect(Collectors.toList());
                sb.append("成本费用项已存在专业:").append(StrUtil.join(",", existNames));
                List<String> existIds = cusFbChapters.stream().map(CusFbChapter::getId).collect(Collectors.toList());
                // 过滤数据
                zh_zjs = zh_zjs.stream().filter(e -> !existIds.contains(e.getSPECID())).collect(Collectors.toList());
                zh_fyxes = zh_fyxes.stream().filter(e -> !existIds.contains(e.getSPECID())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(zh_fyxes)) {
                    List<String> fxyIds = zh_fyxes.stream().map(ZH_FYX::getBM).collect(Collectors.toList());
                    zh_link_gxes = zh_link_gxes.stream().filter(e -> fxyIds.contains(e.getFYXBM())).collect(Collectors.toList());
                    zh_link_tzs = zh_link_tzs.stream().filter(e -> fxyIds.contains(e.getFYXBM())).collect(Collectors.toList());
                } else {
                    zh_link_gxes = new ArrayList<>();
                    zh_link_tzs = new ArrayList<>();
                }
            }
        }

        List<CusFbChapter> fbChapters = new ArrayList<>();
        for (ZH_ZJ zh_zj : zh_zjs) {
            CusFbChapter fb = new CusFbChapter();
            fb.setId(zh_zj.getID());
            fb.setCompanyId(companyId);
            fb.setSpecId(zh_zj.getSPECID());
            fb.setName(zh_zj.getMC());
            fb.setPid(zh_zj.getPID());
            fb.setPids(zh_zj.getPIDS());
            fb.setType(zh_zj.getTYPE());
            fb.setOrderNum(zh_zj.getPX());
            setCreateContent(fb);
            fb.setUserId(userId);
            fb.setDeptId(deptId);
            fbChapters.add(fb);
        }
        if (CollUtil.isNotEmpty(fbChapters)) {
            sb.append("导入成本费用项章节;");
            cusFbChapterMapper.insertBatchSomeColumn(fbChapters);
            fbChapters.clear();
        }



        List<CusFbFee> cusFbFees = new ArrayList<>();
        for (ZH_FYX zf : zh_fyxes) {
            CusFbFee fb = new CusFbFee();
            fb.setId(zf.getBM());
            fb.setCompanyId(companyId);
            fb.setSpecId(zf.getSPECID());
            fb.setName(zf.getMC());
            fb.setChapterId(zf.getFLID());
            fb.setUnit(zf.getDW());
            fb.setContent(zf.getGZNR());
            fb.setCalcRule(zf.getJSGZ());
            fb.setSuitableRange(zf.getGZFW());
            fb.setOrderNum(zf.getPX());
            setCreateContent(fb);
            fb.setUserId(userId);
            fb.setDeptId(deptId);
            cusFbFees.add(fb);
        }
        if (CollUtil.isNotEmpty(cusFbFees)) {
            sb.append("导入成本费用项;");
            cusFbFeeMapper.insertBatchSomeColumn(cusFbFees);
            cusFbFees.clear();
        }


        List<CusLinkFbGx> cusLinkFbGxes = new ArrayList<>();
        for (ZH_LINK_GX zlg : zh_link_gxes) {
            CusLinkFbGx fg = new CusLinkFbGx();
            fg.setId(zlg.getID());
            fg.setCompanyId(companyId);
            fg.setFbId(zlg.getFYXBM());
            fg.setGxId(zlg.getGXID());
            fg.setEnable("Y");
            fg.setSort(zlg.getSORT());
            cusLinkFbGxes.add(fg);
        }

        if (CollUtil.isNotEmpty(cusLinkFbGxes)) {
            sb.append("导入成本费用项关联标准费用项;");
            cusLinkFbGxMapper.insertBatchSomeColumn(cusLinkFbGxes);
            cusLinkFbGxes.clear();
        }


        List<CusLinkFbFeature> fbFeatures = new ArrayList<>();
        for (ZH_LINK_TZ zlt : zh_link_tzs) {
            CusLinkFbFeature fbFeature = new CusLinkFbFeature();
            fbFeature.setId(zlt.getID());
            fbFeature.setCompanyId(companyId);
            fbFeature.setItemId(zlt.getFYXBM());
            fbFeature.setFeatureId(zlt.getTZID());
            fbFeature.setFeatureItem(zlt.getTZZ());
            fbFeature.setEnable("Y");
            fbFeatures.add(fbFeature);
        }
        if (CollUtil.isNotEmpty(fbFeatures)) {
            sb.append("导入成本费用项关联特征;");
            cusLinkFbFeatureMapper.insertBatchSomeColumn(fbFeatures);
            fbFeatures.clear();
        }
        */

        CusImport cusImport = new CusImport();
        cusImport.setCompanyId(companyId);
        cusImport.setFileName(fileName);
        cusImport.setFileSize(fileSize);
        cusImport.setFilePath(filePath);
        cusImport.setInvolveData(sb.toString());
        return cusImportMapper.insert(cusImport);
    }

    @Autowired
    private ShortCusExpenseCategoriesMapper shortCusExpenseCategoriesMapper;
    @Autowired
    private ShortCusFeatureMapper shortCusFeatureMapper;
    @Autowired
    private ShortCusGkUseDataMapper shortCusGkUseDataMapper;
    @Autowired
    private ShortCusMaterialCuChapterMapper shortCusMaterialCuChapterMapper;
    @Autowired
    private ShortCusMaterialCuItemMapper shortCusMaterialCuItemMapper;
    @Autowired
    private ShortCusMechanicalStaChapterMapper shortCusMechanicalStaChapterMapper;
    @Autowired
    private ShortCusMechanicalStaItemMapper shortCusMechanicalStaItemMapper;
    @Autowired
    private ShortCusGxChapterMapper shortCusGxChapterMapper;
    @Autowired
    private ShortCusGxFeatureConsumeMapper shortCusGxFeatureConsumeMapper;
    @Autowired
    private ShortCusGxFeeMapper shortCusGxFeeMapper;
    @Autowired
    private ShortCusGxLinkGkMapper shortCusGxLinkGkMapper;
    @Autowired
    private ShortCusGxLinkGkCategoriesMapper shortCusGxLinkGkCategoriesMapper;
    @Autowired
    private ShortCusLinkFeatureMapper shortCusLinkFeatureMapper;
    @Autowired
    private ShortCusLinkGxfeeCategoryMapper shortCusLinkGxfeeCategoryMapper;
    @Autowired
    private ShortCusLinkSubpkConsumeAddressMapper shortCusLinkSubpkConsumeAddressMapper;
    @Autowired
    private ShortCusLinkSubpkConsumeMapper shortCusLinkSubpkConsumeMapper;
    @Autowired
    private CusImportPackageMapper cusImportPackageMapper;


    @Override
    @Transactional
    public List<CusAllVo> toLead(CusImpVo vo) {
        Long companyId = SecurityUtils.getCompanyId();
        String fileId = vo.getFileId();
        if(StringUtils.isEmpty(fileId)){
            throw new ServiceException("请先上传文件");
        }

        // 信息统计
        List<CusAllVo> cusAllVoList = new LinkedList<>();
        UploadFile uploadFile = uploadFileMapper.selectById(fileId);
        String fileName = uploadFile.getFileName();
        String filePath = uploadFile.getFilePath();
        // 校验格式
        String temp[]=fileName.split("\\.");
        String fileNameNow=temp[temp.length-1];
        if(!StringUtils.equals(fileNameNow,"dat")){
            throw new ServiceException("请上传格式为dat的文件");
        }
        File newFile = new File(SqliteUpPathConfig.getCuspath() + "/" + filePath);

        String zipTempDirPath = SqliteUpPathConfig.getCuspath() +"/"+ filePath.split("\\.")[0];
        SqliteUtil sqliteUtil = new SqliteUtil();
        try {
            ZipUtils.decompressZip(newFile, zipTempDirPath);
            sqliteUtil.getConnection(zipTempDirPath + "/" + CusConstants.Log_TYPE + CusConstants.EXPORT_FILE_SUFFIX);

            String sql = "SELECT * FROM EXPORT_LOG";
            List<EXPORT_LOG> exportLogs = sqliteUtil.selectListRecord(EXPORT_LOG.class, sql);
            Map<String, List<EXPORT_LOG>> logMap = exportLogs.stream().collect(Collectors.groupingBy(EXPORT_LOG::getTYPE));

            if(logMap.size() == 0){
                throw new ServiceException("获取数据失败");
            }

            EXPORT_LOG exportLogLog;
            if(logMap.containsKey(CusConstants.Log_TYPE)) {
                exportLogLog = logMap.get(CusConstants.Log_TYPE).get(0);
            }else {
                throw new ServiceException("获取数据日志失败");
            }
            int ifExist = cusImportPackageMapper.ifExist(exportLogLog.getPACKAGE_ID(), companyId);
            if(ifExist != 0){
                throw new ServiceException("该文件已经导入过");
            }

            // 清空之前的数据
            cusImportMapper.clearOldData(companyId);

            // 材料
            if (logMap.containsKey(CusConstants.CL_TYPE)) {
                EXPORT_LOG exportLogCl = logMap.get(CusConstants.CL_TYPE).get(0);

                CusAllVo clCount = new CusAllVo();
                clCount.setName(CusConstants.CL_NAME);
                clCount.setType(CusConstants.CL_TYPE);
                clCount.setTypeName(CusConstants.CL_NAME);
                clCount.setNodeCount(exportLogCl.getCOUNT_CATEGORY());
                clCount.setFeeCount(exportLogCl.getCOUNT_FEE());
                cusAllVoList.add(clCount);

                if(StringUtils.isNotEmpty(cusMaterialCuItemMapper.ifExistFee(companyId))){
                    String clPath = zipTempDirPath + "/" + CusConstants.CL_TYPE + CusConstants.EXPORT_FILE_SUFFIX;
                    sqliteUtil.getConnection(clPath);
//                    sql = "select ID id,PID pid,PIDS pids,MC chapterName,PX orderNum FROM CL_ZJ";
//                    List<ShortCusMaterialCuChapter> shortCusMaterialCuChapters = sqliteUtil.selectListRecordCompanyId(ShortCusMaterialCuChapter.class, sql, companyId);
//                    if(CollUtil.isNotEmpty(shortCusMaterialCuChapters)){
//                        shortCusMaterialCuChapterMapper.insertBatchSomeColumn(shortCusMaterialCuChapters);
//                        shortCusMaterialCuChapters.clear();
//                    }

                    int pageNum = 1;
                    int pageSize = 20000;
                    sql = "SELECT ID id,BM code,MC itemName,DW unit,GGXH spec,FLID chapterId,PX orderNum FROM CL_FYX limit " + 0 + "," + pageSize;
                    List<ShortCusMaterialCuItem> shortCusMaterialCuItems = sqliteUtil.selectListRecordCompanyId(ShortCusMaterialCuItem.class, sql, companyId);

                    while (CollUtil.isNotEmpty(shortCusMaterialCuItems)) {
                        if (shortCusMaterialCuItems.size() == 20000) {
                            shortCusMaterialCuItemMapper.insertBatchSomeColumn(shortCusMaterialCuItems);
                            shortCusMaterialCuItems.clear();
                            pageNum ++ ;
                            sql = "SELECT ID id,BM code,MC itemName,DW unit,GGXH spec,FLID chapterId,PX orderNum FROM CL_FYX limit " + (pageNum-1)*pageSize + "," + pageSize;
                            shortCusMaterialCuItems = sqliteUtil.selectListRecordCompanyId(ShortCusMaterialCuItem.class, sql, companyId);
                        }
                        if (CollUtil.isNotEmpty(shortCusMaterialCuItems)) {
                            shortCusMaterialCuItemMapper.insertBatchSomeColumn(shortCusMaterialCuItems);
                            shortCusMaterialCuItems.clear();
                        }
                    }

                    sql = "SELECT ID id,FYXBM itemId, TZID featureId,TZZ featureItem,'CL' type, PX orderNum FROM LINK_TZ";
                    List<ShortCusLinkFeature> shortCusLinkFeatures = sqliteUtil.selectListRecordCompanyId(ShortCusLinkFeature.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusLinkFeatures)) {
                        shortCusLinkFeatureMapper.insertBatchSomeColumn(shortCusLinkFeatures);
                        shortCusLinkFeatures.clear();
                    }
                }
            }

            // 机械
            if (logMap.containsKey(CusConstants.JX_TYPE)) {
                EXPORT_LOG exportLogJx = logMap.get(CusConstants.JX_TYPE).get(0);

                CusAllVo jxCount = new CusAllVo();
                jxCount.setName(CusConstants.JX_NAME);
                jxCount.setType(CusConstants.JX_TYPE);
                jxCount.setTypeName(CusConstants.JX_NAME);
                jxCount.setNodeCount(exportLogJx.getCOUNT_CATEGORY());
                jxCount.setFeeCount(exportLogJx.getCOUNT_FEE());
                cusAllVoList.add(jxCount);

                if (StringUtils.isNotEmpty(cusMechanicalStaItemMapper.ifExistFee(companyId))) {
                    String jxPath = zipTempDirPath + "/" + CusConstants.JX_TYPE + CusConstants.EXPORT_FILE_SUFFIX;
                    sqliteUtil.getConnection(jxPath);
                    sql = "select ID id,BM code,MC itemName,DW unit,GGXH spec,GHXS dissipation,FLID chapterId,PX orderNum FROM JX_FYX";
                    List<ShortCusMechanicalStaItem> shortCusMechanicalStaItems = sqliteUtil.selectListRecordCompanyId(ShortCusMechanicalStaItem.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusMechanicalStaItems)) {
                        shortCusMechanicalStaItemMapper.insertBatchSomeColumn(shortCusMechanicalStaItems);
                        shortCusMechanicalStaItems.clear();
                    }
                    sql = "SELECT ID id, SPECID specId,FYXBM itemId, TZID featureId,TZZ featureItem,'JX' type, PX orderNum FROM LINK_TZ";
                    List<ShortCusLinkFeature> shortCusLinkFeatures = sqliteUtil.selectListRecordCompanyId(ShortCusLinkFeature.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusLinkFeatures)) {
                        shortCusLinkFeatureMapper.insertBatchSomeColumn(shortCusLinkFeatures);
                        shortCusLinkFeatures.clear();
                    }
                }
            }

            // 字典
            String zdPath = zipTempDirPath + "/"+ CusConstants.ZD_TYPE + CusConstants.EXPORT_FILE_SUFFIX;
            sqliteUtil.getConnection(zdPath);

            sql = "SELECT ID id,MC categoriesName,DW unit,BZ categoriesRemark,GGXH spec,TYPE type,GKITEM gkItem,PX orderNum FROM ZD_LB";
            List<ShortCusExpenseCategories> shortCusExpenseCategories = sqliteUtil.selectListRecordCompanyId(ShortCusExpenseCategories.class, sql,companyId);
            sql = "SELECT ID id,MC featureName,BIEMING aliasName,MJTZZ featureValues,TYPE type,IsINPUT isInput,PX orderNum FROM ZD_TZ";
            List<ShortCusFeature> shortCusFeatures = sqliteUtil.selectListRecordCompanyId(ShortCusFeature.class, sql,companyId);
            if(shortCusExpenseCategories.size() != 0) shortCusExpenseCategoriesMapper.insertBatchSomeColumn(shortCusExpenseCategories);
            if(shortCusFeatures.size() != 0) shortCusFeatureMapper.insertBatchSomeColumn(shortCusFeatures);

            /*
                2023-08-18 之后还未解除注释则可删除
             */
//            if (StringUtils.isEmpty(gkUseDataMapper.ifExistFee(companyId))) {
//                sql = "select ID id,TEMPLATEID templateId,CODEDESC codeDesc,VALUESTR valueStr,NAMESTR nameStr,LINKID linkId,ORDERNUM orderNum from ZD_GK";
//                List<ShortCusGkUseData> shortCusGkUseData = sqliteUtil.selectListRecordCompanyId(ShortCusGkUseData.class, sql, companyId);
//                if (shortCusGkUseData.size() != 0) shortCusGkUseDataMapper.insertBatchSomeColumn(shortCusGkUseData);
//            }

            // 标准费用项
            if (logMap.containsKey(CusConstants.GX_TYPE)) {
                List<EXPORT_LOG> exportLogGxList = logMap.get(CusConstants.GX_TYPE);
                for (EXPORT_LOG export_log : exportLogGxList) {
                    String specId = export_log.getSPEC_ID();

                    CusAllVo gxCount = new CusAllVo();
                    gxCount.setName(specId);
                    gxCount.setSpecId(specId);
                    gxCount.setType(CusConstants.GX_TYPE);
                    gxCount.setTypeName(CusConstants.GX_NAME);
                    Integer nodeCount = export_log.getCOUNT_CATEGORY();
                    if (NumberUtil.equals(nodeCount, 0)) {
                        gxCount.setNodeCount(-1);
                    } else {
                        gxCount.setNodeCount(nodeCount);
                    }
                    gxCount.setFeeCount(export_log.getCOUNT_FEE());
                    cusAllVoList.add(gxCount);

                    String gxPath = zipTempDirPath + "/" + CusConstants.GX_TYPE + "-" + specId + CusConstants.EXPORT_FILE_SUFFIX;
                    sqliteUtil.getConnection(gxPath);
                    List<ShortCusGxChapter> shortCusGxChapters = new ArrayList<>();
                    if (StringUtils.isEmpty(cusGxFeeMapper.ifExistFee(companyId, specId))) {
                        sql = "SELECT ID id,PID pid,PIDS pids, MC name, PX orderNum, SPECID specId FROM GX_ZJ";
                        shortCusGxChapters = sqliteUtil.selectListRecordCompanyId(ShortCusGxChapter.class, sql, companyId);
                        if (CollUtil.isNotEmpty(shortCusGxChapters)) {
                            shortCusGxChapterMapper.insertBatchSomeColumn(shortCusGxChapters);
                        } else {
                            throw new ServiceException("数据包内 " + specId + " 专业没有章节");
                        }
                    }
                    sql = "SELECT ID id, BM code, MC name , DW unit, GZNR content, JSGZ calcRule, GZFW suitableRange, FLID chapterId, PX orderNum, SPECID specId, YXJ priority, FEATURE_CONSUME_STATE featureConsumeState FROM GX_FYX";
                    List<ShortCusGxFee> shortCusGxFees = sqliteUtil.selectListRecordCompanyId(ShortCusGxFee.class, sql, companyId);
                    shortCusGxFeeMapper.insertBatchSomeColumn(shortCusGxFees);

                    sql = "SELECT ID id, FYXBM gxId, LBID categoryId, TYPE type,SPECID specId,GK_ITEM gkItem FROM GX_LINK_CATEGORY";
                    List<ShortCusLinkGxfeeCategory> shortCusLinkGxfeeCategories = sqliteUtil.selectListRecordCompanyId(ShortCusLinkGxfeeCategory.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusLinkGxfeeCategories)) {
                        shortCusLinkGxfeeCategoryMapper.insertBatchSomeColumn(shortCusLinkGxfeeCategories);
                    }
                    sql = "SELECT ID id, SPEC_ID specId, GX_ID gxId, ADDRESS address, FEATURE_ITEM featureItem, ORDER_NUM orderNum FROM GX_FEATURE_CONSUME";
                    List<ShortCusGxFeatureConsume> shortCusGxFeatureConsumes = sqliteUtil.selectListRecordCompanyId(ShortCusGxFeatureConsume.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusGxFeatureConsumes)) {
                        shortCusGxFeatureConsumeMapper.insertBatchSomeColumn(shortCusGxFeatureConsumes);
                    }
                    sql = "SELECT ID id, ZY specId, DQ address, PX orderNum FROM ADDRESS";
                    List<ShortCusLinkSubpkConsumeAddress> shortCusLinkSubpkConsumeAddresses = sqliteUtil.selectListRecordCompanyId(ShortCusLinkSubpkConsumeAddress.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusLinkSubpkConsumeAddresses)) {
                        shortCusLinkSubpkConsumeAddressMapper.insertBatchSomeColumn(shortCusLinkSubpkConsumeAddresses);
                    }
                    sql = "SELECT ID id, DQ address, ZY specId, GXID subpkItemId, LINK_GX_FEATURE_ID linkGxFeatureId, LINK_ID linkId, CJID categoriesId, XHL consume, TYPE type FROM SL_CONSUME";
                    List<ShortCusLinkSubpkConsume> shortCusLinkSubpkConsumes = sqliteUtil.selectListRecordCompanyId(ShortCusLinkSubpkConsume.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusLinkSubpkConsumes)) {
                        shortCusLinkSubpkConsumeMapper.insertBatchSomeColumn(shortCusLinkSubpkConsumes);
                    }
                    sql = "SELECT id id, GX_ID gxId, SPEC_ID specId, SUBPACKAGE_PATTERN subpackagePattern, TYPE type, FEATURE_STATE featureState, FEATURE_ID featureId, FEATURE_ITEM featureItem ,GK_ITEM gkItem, ORDER_NUM orderNum   FROM GX_LINK_GK";
                    List<ShortCusGxLinkGk> shortCusGxLinkGks = sqliteUtil.selectListRecordCompanyId(ShortCusGxLinkGk.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusGxLinkGks)) {
                        shortCusGxLinkGkMapper.insertBatchSomeColumn(shortCusGxLinkGks);
                    }
                    sql = "SELECT ID id, SPEC_ID specId, GX_ID gxId, GX_LINK_GK_ID gxLinkGkId, CATEGORIES_ID categoriesId, GK_ITEM gkItem, ORDER_NUM orderNum FROM GX_LINK_GK_LB";
                    List<ShortCusGxLinkGkCategories> shortCusGxLinkGkCategories = sqliteUtil.selectListRecordCompanyId(ShortCusGxLinkGkCategories.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusGxLinkGkCategories)) {
                        shortCusGxLinkGkCategoriesMapper.insertBatchSomeColumn(shortCusGxLinkGkCategories);
                    }
                    sql = "SELECT ID id, SPECID specId,FYXBM itemId, TZID featureId,'GX' type, PX orderNum,SPECID specId FROM LINK_TZ";
                    List<ShortCusLinkFeature> shortCusLinkFeatures = sqliteUtil.selectListRecordCompanyId(ShortCusLinkFeature.class, sql, companyId);
                    if (CollUtil.isNotEmpty(shortCusLinkFeatures)) {
                        shortCusLinkFeatureMapper.insertBatchSomeColumn(shortCusLinkFeatures);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            sqliteUtil.relase();
        }
        return cusAllVoList;
    }

    /**
     * 修改CusImport
     *
     * @param cusImport CusImport
     * @return 结果
     */
    @Override
    public int updateCusImport(CusImport cusImport)
    {
        return cusImportMapper.updateById(cusImport);
    }

    /**
     * 批量删除CusImport
     *
     * @param ids 需要删除的CusImport主键
     * @return 结果
     */
    @Override
    public int deleteCusImportByIds(String[] ids)
    {
        return cusImportMapper.deleteCusImportByIds(ids);
    }

    /**
     * 删除CusImport信息
     *
     * @param id CusImport主键
     * @return 结果
     */
    @Override
    public int deleteCusImportById(String id)
    {
        return cusImportMapper.deleteCusImportById(id);
    }

    @Override
    public String disposeFile(MultipartFile file){
        String path = SqliteUpPathConfig.getCuspath();
        if (StrUtil.isEmpty(path)) {
            throw new ServiceException("文件模块暂不支持上传");
        }
        UploadFile fileupload = new UploadFile();
        String name = file.getOriginalFilename();
        fileupload.setFileName(name);
        // 文件后缀名
        String suffix = FileUtil.getSuffix(name);
        if(!StringUtils.equalsAny(suffix,"dat","xls","xlsx")){
            throw new ServiceException("请上传dat/excel文件!");
        }
        String reName = IdUtil.fastUUID();
        String allReName = reName + (StrUtil.isEmpty(suffix) ? "" : "." + suffix);
        File saveFile = new File(path, allReName);

        try {
            // 将文件存放在目录下
            FileUtil.writeFromStream(file.getInputStream(), saveFile);
            Tika tika = new Tika();
            String mimeType = tika.detect(saveFile);
            if (!StringUtils.equals(mimeType, "application/zip")) {
                FileUtil.del(saveFile);
                if (StrUtil.containsAny(mimeType, "application/x-dosexec", "application/x-sh", "application/javascript", "application/x-msdownload", "text/html")) {
                    // 危险操作，停用用户，删除文件
                    throw new ServiceException("危险操作");
                } else {
                    throw new ServiceException("请上传dat文件");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传失败");
        }
        fileupload.setFileSize(FileUtil.readableFileSize(saveFile));
        fileupload.setFilePath(allReName);
        uploadFileMapper.insert(fileupload);
        return fileupload.getId();
    }

    @Override
    public String uploadExcel(MultipartFile file) {
        String path = SqliteUpPathConfig.getCuspath();
        if (StrUtil.isEmpty(path)) {
            throw new ServiceException("文件模块暂不支持上传");
        }
        UploadFile fileupload = new UploadFile();
        String name = file.getOriginalFilename();
        fileupload.setFileName(name);
        // 文件后缀名
        String suffix = FileUtil.getSuffix(name);
        if(!StrUtil.containsAny(suffix,"xls","xlsx")){
            throw new ServiceException("请上传Excel文件!");
        }
        String reName = IdUtil.fastUUID();
        String allReName = reName + (StrUtil.isEmpty(suffix) ? "" : "." + suffix);
        File saveFile = new File(path, allReName);
        try {
            // 将文件存放在目录下
            FileUtil.writeFromStream(file.getInputStream(), saveFile);
            Tika tika = new Tika();
            String mimeType = tika.detect(saveFile);
            if (!StringUtils.equals(mimeType, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                FileUtil.del(saveFile);
                throw new ServiceException("请上传Excel文件");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传失败");
        }
        fileupload.setFileSize(FileUtil.readableFileSize(saveFile));
        fileupload.setFilePath(allReName);
        uploadFileMapper.insert(fileupload);
        return fileupload.getId();
    }
    @Override
    public int delFile(String id) {
        UploadFile uploadFile = uploadFileMapper.selectById(id);
        String filePath = uploadFile.getFilePath();
        String path = SqliteUpPathConfig.getCuspath();
        FileUtil.del(new File(path,filePath));
        return uploadFileMapper.deleteById(id);
    }

    private String getPids(String code, List<ExcelChapterVo> list, List<String> result) {
        //循环遍历list
        for (ExcelChapterVo chapterVo : list) {

            //判断节点和传过来的参数是否相同，如果相同获取节点名称
            if (code.equals(chapterVo.getCode())) {
                result.add(chapterVo.getCode());//将获取到的节点名称，添加到list集合中
                getPids(chapterVo.getPid(), list, result);//递归方法
            }
        }
        String pids = ""; //定义一个字符串
        //拼接返回值,排序(倒序)
        for (int i = result.size() - 1; i >= 0; i--) {
            pids += result.get(i) + ",";
        }
        //去除字符串后面的连接符“-”
        if (pids.length() > 0) {
            pids = pids.substring(0, pids.length() - 1);
        }
        return pids;
    }

    @Override
    @Transactional
    public Map<String, Integer> insertCusMaterialImport(CusImpVo vo) {
        Long companyId = SecurityUtils.getCompanyId();
        String fileId = vo.getFileId();
        UploadFile uploadFile = uploadFileMapper.selectById(fileId);
        String fileName = uploadFile.getFileName();
        String fileSize = uploadFile.getFileSize();
        String filePath = uploadFile.getFilePath();
        String path = SqliteUpPathConfig.getCuspath();
        // 校验格式
        String temp[]=fileName.split("\\.");
        String fileNameNow=temp[temp.length-1];
        if(!StringUtils.equals(fileNameNow,"xlsx") && !StringUtils.equals(fileNameNow,"xls")){
            throw new ServiceException("请上传excel文件!");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();
        Long deptId = loginUser.getDeptId();
        String username = user.getUserName();
        String nickName = user.getNickName();
        String byUser = username + Constants.NAME_SEPARATOR + nickName;
        if (deptId == null ) {
            deptId = -999L;
        }
        String excelPath = path + "/" + filePath;
        // 读取excel
        InputStream inputStream = FileUtil.getInputStream(excelPath);
        if (inputStream == null) {
            throw new ServiceException("对应文件不存在,请联系管理员");
        }

        //监视器
        ExcelListener listener = new ExcelListener();

        ExcelReader excelReader = EasyExcel.read(inputStream, listener).build();
        // 第一个sheet读取类型
        ReadSheet readSheet1 = EasyExcel.readSheet("费用项目录").head(ExcelChapterVo.class).headRowNumber(2).build();
        // 第二个sheet读取类型
        ReadSheet readSheet2 = EasyExcel.readSheet("费用项").head(ExcelItemVo.class).headRowNumber(2).build();

        // 开始读取第一个sheet
        excelReader.read(readSheet1);
        //excel sheet1 信息
        long id = System.currentTimeMillis();
        List<ExcelChapterVo> chapterList = listener.getDataList();
        for (ExcelChapterVo chapterVo : chapterList) {
            chapterVo.setCode(Long.toString(id) + chapterVo.getCode());
            chapterVo.setPid("0".equals(chapterVo.getPid()) ? "0" : Long.toString(id) + chapterVo.getPid());
        }
        List result = new ArrayList();
        List<CusMaterialChapter> chapters = new ArrayList<>();
        Integer countChapter = 0;
        for (int i = 0; i < chapterList.size(); i++) {
            result.clear();
            ExcelChapterVo chapterVo = chapterList.get(i);
            CusMaterialChapter chapter = new CusMaterialChapter();
            chapter.setId(chapterVo.getCode());
            chapter.setPid(chapterVo.getPid());
            chapter.setChapterName(chapterVo.getName());
            // pids
            chapter.setPids("0,"+getPids(chapterVo.getCode(), chapterList, result));
            chapter.setOrderNum(i+1);
            chapter.setCompanyId(companyId);
            chapter.setUserId(userId);
            chapter.setDeptId(deptId);
            setCreateContent(chapter);
            chapters.add(chapter);

            if(chapters.size() == 10000){
                cusMaterialChapterMapper.insertBatchSomeColumn(chapters);
                countChapter+=10000;
                chapters.clear();
            }
        }
        if(chapters.size() > 0){
            countChapter+=chapters.size();
            cusMaterialChapterMapper.insertBatchSomeColumn(chapters);
        }

        // 清空之前的数据
        listener.getDataList().clear();
        // 开始读取第二个sheet
        excelReader.read(readSheet2);
        //excel sheet2 信息
        List<ExcelItemVo> itemList = listener.getDataList();

        int ordernum = 0;
        String chapter ="";
        List<CusMaterialItem> items = new ArrayList<>();
        Integer countItem = 0;
        for (ExcelItemVo itemVo : itemList) {
            if(!chapter.equals(itemVo.getChapterCode())){
                chapter = itemVo.getChapterCode();
                ordernum = 0;
            }else {
                ordernum ++;
            }
            CusMaterialItem item = new CusMaterialItem();
            item.setChapterId(Long.toString(id) + itemVo.getChapterCode());
            item.setCode(itemVo.getItemCode());
            item.setItemName(itemVo.getItemName());
            item.setUnit(itemVo.getItemUnit());
            item.setSpec(itemVo.getItemSpec());
            item.setOrderNum(ordernum);
            item.setCompanyId(companyId);
            item.setUserId(userId);
            item.setDeptId(deptId);
            setCreateContent(item);
            items.add(item);

            if(items.size() == 10000){
                countItem+=10000;
                cusMaterialItemMapper.insertBatchSomeColumn(items);
                items.clear();
            }

        }
        if(items.size()>0){
            countItem+=items.size();
            cusMaterialItemMapper.insertBatchSomeColumn(items);
        }


        CusImport cusImport = new CusImport();
        cusImport.setCompanyId(companyId);
        cusImport.setFileName(fileName);
        cusImport.setFileSize(fileSize);
        cusImport.setFilePath(filePath);
        cusImport.setInvolveData("材料章节,材料费用项");

        Map<String,Integer> msgMap = new HashMap<>();
        msgMap.put("chapter",countChapter);
        msgMap.put("fee",countItem);
        return msgMap;
    }

    @Override
    @Transactional
    public int materialCopySta() {
        // 复制数据到 客户表
        Long companyId = SecurityUtils.getCompanyId();

        Long chapterCount = cusMaterialChapterMapper.selectCount(
                Wrappers.<CusMaterialChapter>lambdaQuery()
                        .eq(CusMaterialChapter::getCompanyId, companyId)
        );
        Long itemCount = cusMaterialItemMapper.selectCount(
                Wrappers.<CusMaterialItem>lambdaQuery()
                        .eq(CusMaterialItem::getCompanyId, companyId)
        );
        // 获取是否已经存在关联关系
        if (chapterCount > 0 || itemCount > 0) {
            throw new ServiceException("当前已有关联标准材料的数据,无法使用标准材料数据!");
        }

        // 获取标准材料
        Long aLong = cusMaterialCuItemMapper.selectCount(
                Wrappers.<CusMaterialCuItem>lambdaQuery()
                        .eq(CusMaterialCuItem::getCompanyId, companyId)
        );
        if (aLong <= 0) {
            throw new ServiceException("当前无标准材料数据!");
        }
        cusMaterialCuChapterMapper.copyCusMaterialChapter(companyId);
        cusMaterialCuChapterMapper.copyCusMaterialItem(companyId);
        cusLinkFeatureMapper.clearLinkFeature(companyId,CusConstants.CL_TYPE);
        cusLinkFeatureMapper.copyLinkFeature(companyId,CusConstants.CL_TYPE);
        cusMaterialCuChapterMapper.copyLinkCusItemSta(companyId);
        return 1;
    }

    @Override
    public Map<String, Integer> insertCusMechanicalImport(CusImpVo vo) {
        Long companyId = SecurityUtils.getCompanyId();
        String fileId = vo.getFileId();
        UploadFile uploadFile = uploadFileMapper.selectById(fileId);
        String fileName = uploadFile.getFileName();
        String fileSize = uploadFile.getFileSize();
        String filePath = uploadFile.getFilePath();
        String path = SqliteUpPathConfig.getCuspath();
        // 校验格式
        String temp[]=fileName.split("\\.");
        String fileNameNow=temp[temp.length-1];
        if(!StringUtils.equals(fileNameNow,"xlsx") && !StringUtils.equals(fileNameNow,"xls")){
            throw new ServiceException("请上传excel文件!");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();
        Long deptId = loginUser.getDeptId();
        String username = user.getUserName();
        String nickName = user.getNickName();
        String byUser = username + Constants.NAME_SEPARATOR + nickName;
        if (deptId == null ) {
            deptId = -999L;
        }
        String excelPath = path + "/" + filePath;
        // 读取excel
        InputStream inputStream = FileUtil.getInputStream(excelPath);
        if (inputStream == null) {
            throw new ServiceException("对应文件不存在,请联系管理员");
        }
        //监视器
        ExcelListener listener = new ExcelListener();

        ExcelReader excelReader = EasyExcel.read(inputStream, listener).build();
        // 第一个sheet读取类型
        ReadSheet readSheet1 = EasyExcel.readSheet("费用项目录").head(ExcelChapterVo.class).headRowNumber(2).build();
        // 第二个sheet读取类型
        ReadSheet readSheet2 = EasyExcel.readSheet("费用项").head(ExcelItemVo.class).headRowNumber(2).build();

        // 开始读取第一个sheet
        excelReader.read(readSheet1);
        //excel sheet1 信息
        long id = System.currentTimeMillis();
        List<ExcelChapterVo> chapterList = listener.getDataList();
        for (ExcelChapterVo chapterVo : chapterList) {
            chapterVo.setCode(Long.toString(id) + chapterVo.getCode());
            chapterVo.setPid("0".equals(chapterVo.getPid()) ? "0" : Long.toString(id) + chapterVo.getPid());
        }
        List result = new ArrayList();
        List<CusMechanicalChapter> chapters = new ArrayList<>();
        Integer countChapter = 0;
        for (int i = 0; i < chapterList.size(); i++) {
            result.clear();
            ExcelChapterVo chapterVo = chapterList.get(i);
            CusMechanicalChapter chapter = new CusMechanicalChapter();
            chapter.setId(chapterVo.getCode());
            chapter.setPid(chapterVo.getPid());
            chapter.setChapterName(chapterVo.getName());
            // pids
            chapter.setPids("0,"+getPids(chapterVo.getCode(), chapterList, result));
            chapter.setOrderNum(i+1);
            chapter.setCompanyId(companyId);
            chapter.setUserId(userId);
            chapter.setDeptId(deptId);
            setCreateContent(chapter);
            chapters.add(chapter);

            if(chapters.size() == 10000){
                cusMechanicalChapterMapper.insertBatchSomeColumn(chapters);
                countChapter+=10000;
                chapters.clear();
            }
        }
        if(chapters.size() > 0){
            countChapter+=chapters.size();
            cusMechanicalChapterMapper.insertBatchSomeColumn(chapters);
        }

        // 清空之前的数据
        listener.getDataList().clear();
        // 开始读取第二个sheet
        excelReader.read(readSheet2);
        //excel sheet2 信息
        List<ExcelItemVo> itemList = listener.getDataList();

        int ordernum = 0;
        String chapter ="";
        List<CusMechanicalItem> items = new ArrayList<>();
        Integer countItem = 0;
        for (ExcelItemVo itemVo : itemList) {
            if(!chapter.equals(itemVo.getChapterCode())){
                chapter = itemVo.getChapterCode();
                ordernum = 0;
            }else {
                ordernum ++;
            }
            CusMechanicalItem item = new CusMechanicalItem();
            item.setChapterId(Long.toString(id) + itemVo.getChapterCode());
            item.setCode(itemVo.getItemCode());
            item.setItemName(itemVo.getItemName());
            item.setUnit(itemVo.getItemUnit());
            item.setSpec(itemVo.getItemSpec());
            item.setOrderNum(ordernum);
            item.setCompanyId(companyId);
            item.setUserId(userId);
            item.setDeptId(deptId);
            setCreateContent(item);
            items.add(item);

            if(items.size() == 10000){
                countItem+=10000;
                cusMechanicalItemMapper.insertBatchSomeColumn(items);
                items.clear();
            }
        }
        if(items.size()>0){
            countItem+=items.size();
            cusMechanicalItemMapper.insertBatchSomeColumn(items);
        }

        CusImport cusImport = new CusImport();
        cusImport.setCompanyId(companyId);
        cusImport.setFileName(fileName);
        cusImport.setFileSize(fileSize);
        cusImport.setFilePath(filePath);
        cusImport.setInvolveData("机械章节,机械费用项");
        cusImportMapper.insert(cusImport);

        Map<String,Integer> msgMap = new HashMap<>();
        msgMap.put("chapter",countChapter);
        msgMap.put("fee",countItem);
        return msgMap;
    }

    @Override
    @Transactional
    public int mechanicalCopySta() {
        // 复制数据到 客户表
        Long companyId = SecurityUtils.getCompanyId();

        // 获取是否已经存在关联关系
        Long existLinkCount = cusLinkMechanicalStaCusMapper.selectCount(
                Wrappers.<CusLinkMechanicalStaCus>lambdaQuery()
                        .eq(CusLinkMechanicalStaCus::getCompanyId, companyId)
        );
        if (existLinkCount > 0) {
            throw new ServiceException("当前已有关联标准机械的数据,无法使用标准机械数据!");
        }

        // 获取标准材料
        Long aLong = cusMechanicalStaItemMapper.selectCount(
                Wrappers.<CusMechanicalStaItem>lambdaQuery()
                        .eq(CusMechanicalStaItem::getCompanyId, companyId)
        );
        if (aLong <= 0) {
            throw new ServiceException("当前无标准机械数据!");
        }
        cusMechanicalStaChapterMapper.copyCusMechanicalChapter(companyId);
        cusMechanicalStaChapterMapper.copyCusMechanicalItem(companyId);
        cusLinkFeatureMapper.clearLinkFeature(companyId,CusConstants.JX_TYPE);
        cusLinkFeatureMapper.copyLinkFeature(companyId,CusConstants.JX_TYPE);
        cusMechanicalStaChapterMapper.copyLinkMechanicalCusItemSta(companyId);
        return 1;
    }

    @Override
    @Transactional
    public List<CusCountDifferenceVo> countDifference(List<CusAllVo> cusAllVoList) {
        Long companyId = SecurityUtils.getCompanyId();
        List<CusCountDifferenceVo> voList = new LinkedList<>();
        Map<String, List<CusAllVo>> groupByTypeMap = cusAllVoList.stream().collect(Collectors.groupingBy(CusAllVo::getType));
        if (groupByTypeMap.containsKey(CusConstants.CL_TYPE)) {
            cusImportMapper.countClDifference(companyId);
            CusCountDifferenceVo clCount = shortDifferenceMapper.getCount(companyId, CusConstants.CL_TYPE, null);
            clCount.setName("材料费用项");
            if (clCount.getCountI() + clCount.getCountU() + clCount.getCountD() == 0) {
                if (StringUtils.isEmpty(cusMaterialCuItemMapper.ifExistFee(companyId))) {
                    clCount.setRemark("需全部导入");
                } else {
                    clCount.setRemark("已是最新版本");
                }
            }
            voList.add(clCount);
        }
        if (groupByTypeMap.containsKey(CusConstants.JX_TYPE)) {
            cusImportMapper.countJxDifference(companyId);
            CusCountDifferenceVo jxCount = shortDifferenceMapper.getCount(companyId, CusConstants.JX_TYPE, null);
            jxCount.setName("机械费用项");
            if (jxCount.getCountI() + jxCount.getCountU() + jxCount.getCountD() == 0) {
                if (StringUtils.isEmpty(cusMechanicalStaItemMapper.ifExistFee(companyId))) {
                    jxCount.setRemark("需全部导入");
                } else {
                    jxCount.setRemark("已是最新版本");
                }
            }
            voList.add(jxCount);
        }
        if(groupByTypeMap.containsKey(CusConstants.GX_TYPE)){
            List<SysDictData> fee_projecttype = DictUtils.getDictCache("fee_projecttype");
            Map<String, String> dictMap = null;
            if (fee_projecttype != null) {
                dictMap = fee_projecttype.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            } else {
                throw new RuntimeException("专业字典获取失败，请联系管理员");
            }
            for (CusAllVo cusAllVo : groupByTypeMap.get(CusConstants.GX_TYPE)) {
                String specId = cusAllVo.getSpecId();
                cusImportMapper.countGxDifference(companyId,specId);
                CusCountDifferenceVo gxCount = shortDifferenceMapper.getCount(companyId, CusConstants.GX_TYPE, specId);
                gxCount.setName(dictMap.get(specId) + "标准费用项");
                voList.add(gxCount);
            }
        }
        return voList;
    }
    @Autowired
    private CusImportDetailsMapper cusImportDetailsMapper;

    @Override
    @Transactional
    public int toCover(CusImpVo vo) {
        String fileId = vo.getFileId();

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptId = -999L;
        Long userId = SecurityUtils.getUserId();
        String createBy = user.getUserName() + "@_@" + user.getNickName();

        Long companyId = SecurityUtils.getCompanyId();
        List<CusImportDetails> cusImportDetailsList = new ArrayList<>();

        UploadFile uploadFile = uploadFileMapper.selectById(fileId);
        String fileName = uploadFile.getFileName();
        String filePath = uploadFile.getFilePath();
        String uuid = filePath.split("\\.")[0];
        String zipTempDirPath = SqliteUpPathConfig.getCuspath() +"/"+ uuid + "/";

        SqliteUtil sqliteUtil = new SqliteUtil();
        sqliteUtil.getConnection( zipTempDirPath + CusConstants.Log_TYPE + CusConstants.EXPORT_FILE_SUFFIX);

        String sql = "SELECT * FROM EXPORT_LOG";
        List<EXPORT_LOG> exportLogs = sqliteUtil.selectListRecord(EXPORT_LOG.class, sql);
        Map<String, List<EXPORT_LOG>> logMap = exportLogs.stream().collect(Collectors.groupingBy(EXPORT_LOG::getTYPE));

        EXPORT_LOG exportLogLog;
        if(logMap.containsKey(CusConstants.Log_TYPE)) {
            exportLogLog = logMap.get(CusConstants.Log_TYPE).get(0);
        }else {
            throw new ServiceException("获取数据日志失败");
        }
        String packageUuid = exportLogLog.getPACKAGE_ID();

        CusImportPackage cusImportPackage = new CusImportPackage();
        cusImportPackage.setId(packageUuid);
        cusImportPackage.setCompanyId(companyId);
        cusImportPackage.setName(fileName);
        cusImportPackage.setInvolveData(exportLogLog.getNAME());
        cusImportPackage.setFileSize(uploadFile.getFileSize());
        cusImportPackage.setFilePath(filePath);

        Integer orderNum = 0;
        cusImportMapper.toCoverZd(companyId,userId,deptId,createBy);
        if (StringUtils.isEmpty(gkUseDataMapper.ifExistFee(companyId))) {
            // 字典
            String zdPath = zipTempDirPath + "/"+ CusConstants.ZD_TYPE + CusConstants.EXPORT_FILE_SUFFIX;
            sqliteUtil.getConnection(zdPath);
            sql = "select ID id,TEMPLATEID templateId,CODEDESC codeDesc,VALUESTR valueStr,NAMESTR nameStr,LINKID linkId,ORDERNUM orderNum from ZD_GK";
            List<GkUseData> gkUseDataList = sqliteUtil.selectListRecordCompanyId(GkUseData.class, sql, companyId);
            if (gkUseDataList.size() != 0) gkUseDataMapper.insertBatchSomeColumn(gkUseDataList);
        }

        if(logMap.containsKey(CusConstants.CL_TYPE)){
            cusMaterialCuChapterMapper.deleteByCompanyId(companyId);
            String clPath = zipTempDirPath + "/" + CusConstants.CL_TYPE + CusConstants.EXPORT_FILE_SUFFIX;
            sqliteUtil.getConnection(clPath);
            sql = "select ID id,PID pid,PIDS pids,MC chapterName,PX orderNum FROM CL_ZJ";
            List<CusMaterialCuChapter> cusMaterialCuChapters = sqliteUtil.selectListRecordCompanyId(CusMaterialCuChapter.class, sql, companyId);

            for (CusMaterialCuChapter cusMaterialCuChapter : cusMaterialCuChapters) {
                setCreateContent(cusMaterialCuChapter);
                cusMaterialCuChapter.setUserId(userId);
                cusMaterialCuChapter.setDeptId(deptId);
            }
            cusMaterialCuChapterMapper.insertBatchSomeColumn(cusMaterialCuChapters);
            cusMaterialCuChapters.clear();

            if(StringUtils.isEmpty(cusMaterialCuItemMapper.ifExistFee(companyId))){
                int pageNum = 1;
                int pageSize = 20000;
                sql = "SELECT ID id,BM code,MC itemName,DW unit,GGXH spec,FLID chapterId,PX orderNum FROM CL_FYX limit " + 0 + "," + pageSize;
                List<CusMaterialCuItem> cusMaterialCuItems = sqliteUtil.selectListRecordCompanyId(CusMaterialCuItem.class, sql, companyId);

                while (CollUtil.isNotEmpty(cusMaterialCuItems)) {
                    for (CusMaterialCuItem cusMaterialCuItem : cusMaterialCuItems) {
                        setCreateContent(cusMaterialCuItem);
                        cusMaterialCuItem.setUserId(userId);
                        cusMaterialCuItem.setDeptId(deptId);
                    }
                    if (cusMaterialCuItems.size() == 20000) {
                        cusMaterialCuItemMapper.insertBatchSomeColumn(cusMaterialCuItems);
                        cusMaterialCuItems.clear();
                        pageNum ++ ;
                        sql = "SELECT ID id,BM code,MC itemName,DW unit,GGXH spec,FLID chapterId,PX orderNum FROM CL_FYX limit " + (pageNum-1)*pageSize + "," + pageSize;
                        cusMaterialCuItems = sqliteUtil.selectListRecordCompanyId(CusMaterialCuItem.class, sql, companyId);
                    }
                    if (CollUtil.isNotEmpty(cusMaterialCuItems)) {
                        cusMaterialCuItemMapper.insertBatchSomeColumn(cusMaterialCuItems);
                        cusMaterialCuItems.clear();
                    }
                }

                sql = "SELECT ID id, '' specId,FYXBM itemId, TZID featureId,TZZ featureItem,'CL' type, PX orderNum FROM LINK_TZ";
                List<CusLinkFeatureAsset> clLinkFeatureAssets = sqliteUtil.selectListRecordCompanyId(CusLinkFeatureAsset.class, sql, companyId);
                if (CollUtil.isNotEmpty(clLinkFeatureAssets)) {
                    cusLinkFeatureAssetMapper.insertBatchSomeColumn(clLinkFeatureAssets);
                    clLinkFeatureAssets.clear();
                }
            }else {
                cusImportMapper.toCoverCl(companyId,userId,deptId,createBy);
            }

            ++orderNum;
            EXPORT_LOG exportLogCl = logMap.get(CusConstants.CL_TYPE).get(0);
            CusImportDetails cusImportDetailsCL = new CusImportDetails();
            cusImportDetailsCL.setId(packageUuid + "-" + CusConstants.CL_TYPE);
            cusImportDetailsCL.setCompanyId(companyId);
            cusImportDetailsCL.setPackageId(packageUuid);
            cusImportDetailsCL.setName(CusConstants.CL_NAME);
            cusImportDetailsCL.setCountCategory(exportLogCl.getCOUNT_CATEGORY());
            cusImportDetailsCL.setCountFee(exportLogCl.getCOUNT_FEE());
            cusImportDetailsCL.setType(CusConstants.CL_TYPE);
            cusImportDetailsCL.setSpecId(CusConstants.CL_TYPE);
            cusImportDetailsCL.setOrderNum(orderNum);
            cusImportDetailsList.add(cusImportDetailsCL);
        }

        if(logMap.containsKey(CusConstants.JX_TYPE)){
            cusMechanicalStaChapterMapper.deleteByCompanyId(companyId);
            String jxPath = zipTempDirPath + "/" + CusConstants.JX_TYPE + CusConstants.EXPORT_FILE_SUFFIX;
            sqliteUtil.getConnection(jxPath);
            sql = "select ID id,PID pid,PIDS pids,MC chapterName,PX orderNum FROM JX_ZJ";
            List<CusMechanicalStaChapter> cusMechanicalStaChapters = sqliteUtil.selectListRecordCompanyId(CusMechanicalStaChapter.class, sql, companyId);
            for (CusMechanicalStaChapter cusMaterialCuChapter : cusMechanicalStaChapters) {
                setCreateContent(cusMaterialCuChapter);
                cusMaterialCuChapter.setUserId(userId);
                cusMaterialCuChapter.setDeptId(deptId);
            }
            cusMechanicalStaChapterMapper.insertBatchSomeColumn(cusMechanicalStaChapters);
            cusMechanicalStaChapters.clear();

            if (StringUtils.isEmpty(cusMechanicalStaItemMapper.ifExistFee(companyId))) {
                sql = "select ID id,BM code,MC itemName,DW unit,GGXH spec,GHXS dissipation,FLID chapterId,PX orderNum FROM JX_FYX";
                List<CusMechanicalStaItem> cusMechanicalStaItems = sqliteUtil.selectListRecordCompanyId(CusMechanicalStaItem.class, sql, companyId);

                for (CusMechanicalStaItem cusMechanicalStaItem : cusMechanicalStaItems) {
                    setCreateContent(cusMechanicalStaItem);
                    cusMechanicalStaItem.setUserId(userId);
                    cusMechanicalStaItem.setDeptId(deptId);
                }
                cusMechanicalStaItemMapper.insertBatchSomeColumn(cusMechanicalStaItems);
                cusMechanicalStaItems.clear();

                sql = "SELECT ID id, '' specId,FYXBM itemId, TZID featureId,TZZ featureItem,'JX' type, PX orderNum FROM LINK_TZ";
                List<CusLinkFeatureAsset> jxLinkFeatureAssets = sqliteUtil.selectListRecordCompanyId(CusLinkFeatureAsset.class, sql, companyId);
                if (CollUtil.isNotEmpty(jxLinkFeatureAssets)) {
                    cusLinkFeatureAssetMapper.insertBatchSomeColumn(jxLinkFeatureAssets);
                    jxLinkFeatureAssets.clear();
                }
            } else {
                cusImportMapper.toCoverJx(companyId,userId,deptId,createBy);
            }

            ++orderNum;
            EXPORT_LOG exportLogJx = logMap.get(CusConstants.JX_TYPE).get(0);
            CusImportDetails cusImportDetailsCL = new CusImportDetails();
            cusImportDetailsCL.setId(packageUuid + "-" + CusConstants.JX_TYPE);
            cusImportDetailsCL.setCompanyId(companyId);
            cusImportDetailsCL.setPackageId(packageUuid);
            cusImportDetailsCL.setName(CusConstants.JX_NAME);
            cusImportDetailsCL.setCountCategory(exportLogJx.getCOUNT_CATEGORY());
            cusImportDetailsCL.setCountFee(exportLogJx.getCOUNT_FEE());
            cusImportDetailsCL.setType(CusConstants.JX_TYPE);
            cusImportDetailsCL.setSpecId(CusConstants.JX_TYPE);
            cusImportDetailsCL.setOrderNum(orderNum);
            cusImportDetailsList.add(cusImportDetailsCL);

        }

        if(logMap.containsKey(CusConstants.GX_TYPE)){
//            List<String> specIds = cusGxChapterMapper.selectSpecIdAll(companyId);
//            for (CusAllVo cusAllVo : groupByTypeMap.get(CusConstants.GX_TYPE)) {
//                String specId = cusAllVo.getSpecId();
//                if(!specIds.contains(specId)){
//                    cusGxChapterMapper.insertChapter(companyId,specId,userId,deptId,createBy);
//                }
//            }
            cusImportMapper.toCoverGxAll(companyId,userId,deptId,createBy);

            List<SysDictData> fee_projecttype = DictUtils.getDictCache("fee_projecttype");
            Map<String, String> dictMap = null;
            if (fee_projecttype != null) {
                dictMap = fee_projecttype.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            }

            List<EXPORT_LOG> exportLogList = logMap.get(CusConstants.GX_TYPE);
            for (EXPORT_LOG exportLogGx : exportLogList){
                String specId = exportLogGx.getSPEC_ID();
                ++orderNum;
                CusImportDetails cusImportDetailsGx = new CusImportDetails();
                cusImportDetailsGx.setId(packageUuid + "-" + specId);
                cusImportDetailsGx.setCompanyId(companyId);
                cusImportDetailsGx.setPackageId(packageUuid);
                cusImportDetailsGx.setName(dictMap.get(specId) + CusConstants.GX_NAME);
                cusImportDetailsGx.setCountCategory(exportLogGx.getCOUNT_CATEGORY());
                cusImportDetailsGx.setCountFee(exportLogGx.getCOUNT_FEE());
                cusImportDetailsGx.setType(CusConstants.GX_TYPE);
                cusImportDetailsGx.setSpecId(specId);
                cusImportDetailsGx.setOrderNum(orderNum);
                cusImportDetailsList.add(cusImportDetailsGx);
            }
        }
        if(cusImportDetailsList.size() != 0){
            cusImportDetailsMapper.insertBatchSomeColumn(cusImportDetailsList);
            cusImportPackageMapper.insert(cusImportPackage);
        }

        cusImportMapper.clearOldData(companyId);
        return 200;
    }
}
